<template>
    <div class="common-page page-work-orders" v-loading.fullscreen="loading">
        <div class="common-page__head">
            <!-- <comp-paths class="route" :paths="['/work', $route.fullPath]"></comp-paths> -->
            <div class="title">{{ $options.title }}</div>
        </div>
        <comp-orders class="common-page__body" ref="list" select link>
            <template #head="scope">
                <el-button type="plain" size="small" icon="el-icon-refresh" @click="search()">刷新列表</el-button>
                <el-button type="danger" size="small" icon="el-icon-delete" @click="delOrder(...scope.selects)">删除事项</el-button>
                <el-button type="plain" size="small" icon="el-icon-upload2" @click="importOrders()">导入事项</el-button>
                <el-button v-if="managerQuNums.includes(zh)" type="plain" size="small" icon="el-icon-upload2" @click="toBackOrders()">批量恢复事项</el-button>
                <el-button v-if="managerQuNums.includes(zh)"  type="plain" size="small" icon="el-icon-download" @click="exportOrders()">导出事项</el-button>
            </template>
            <template #body="scope">
                <el-button type="primary" size="mini" @click.stop="getOrder(scope.data)">详情</el-button>
                <el-button type="danger" size="mini" @click.stop="delOrder(scope.data)">删除</el-button>
            </template>
        </comp-orders>
        <comp-dialog title="从 Excel 导入事项" width="360px" ref="ordersImportForm">
            <comp-import template="./data/WorkOrderImportTemplate.xlsx" @start="importOrders('submit', $event)" @end="importOrders('end')"></comp-import>
        </comp-dialog>
        <comp-dialog title="从 Excel 导入恢复事项" width="360px" ref="toBackOrdersImportForm">
            <comp-import template="./data/WorkOrderImportTemplateToBackOver.xlsx" @start="toBackOrders('submit', $event)" @end="toBackOrders('end')"></comp-import>
        </comp-dialog>
    </div>
</template>

<script>
    import mixin from "../mixin";
    import { string, int, deepCopy } from "../util";
    export default {
        name: "page-work-orders",
        title: "全部事项",
        nodes: ["/menu/work"],
        childs: ["work-order"],
        mixins: [mixin],
        data: () => ({
            loading: false,
            zh:'',
            managerQuNums:managerQuNums
        }),
        methods: {
            search() {
                if (this.loading) return;
                this.$nextTick(() => this.$refs.list.init());
            },
            getOrder(order) {
                if (this.loading) return;
                this.$router.push("/work/order?orderId=" + order.id);
            },
            delOrder(...orders) {
                if (this.loading) return;
                if (orders.length === 0) return this.plugins.modal.toast("请先勾选要删除的事项哦！", "warning");
                let content = " <span style='color:red;'>" + (orders.length > 1 ? "勾选的" + orders.length + "个事项" : orders[0].title) + "</span> 吗？";
                this.plugins.modal.alert("删除确认", "确定删除" + content, "warning", ["确定删除", "再想想"]).then((ok) => {
                    if (!ok) return;
                    this.loading = true;
                    this.plugins.user.delOrder(...orders).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("删除成功！", "success");
                            this.search();
                        } else {
                            this.plugins.modal.alert("删除失败", res.code + "：" + res.msg, "error");
                        }
                    });
                });
            },
            importOrders(action, data) {
                if (this.loading) return;
                if (!action || action === "start") {
                    this.$refs.ordersImportForm.init();
                } else if (action === "submit") {
                    this.loading = true;
                    this.plugins.user.importOrders({ file: data }).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.alert("导入任务创建成功！", "任务执行需要花费一些时间，可稍后再点击右上角打开“系统任务”查看任务状态。", "success", ["查看任务状态", "稍后查看"]).then((ok) => ok && this.$router.push("/user/tasks"));
                            this.importOrders("end");
                            this.search();
                        } else {
                            this.plugins.modal.alert("导入失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.ordersImportForm.close();
                }
            },
            toBackOrders(action, data) {
                if (this.loading) return;
                if (!action || action === "start") {
                    this.$refs.toBackOrdersImportForm.init();
                } else if (action === "submit") {
                    this.loading = true;
                    this.plugins.user.importToBackOrders({ file: data }).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.alert("导入任务创建成功！", "任务执行需要花费一些时间，可稍后再点击右上角打开“系统任务”查看任务状态。", "success", ["查看任务状态", "稍后查看"]).then((ok) => ok && this.$router.push("/user/tasks"));
                            this.toBackOrders("end");
                            this.search();
                        } else {
                            this.plugins.modal.alert("导入失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.toBackOrdersImportForm.close();
                }
            },
            exportOrders() {
                if (this.loading) return;
                let filters = deepCopy(this.$refs.list.filters);
                let jbdwlistAll = deepCopy(this.$refs.list.jbdwlistAll)
                let content = "当前筛选条件下的 <span style='color:red;'>全部共" + filters.total + "个事项</span> ";
                if (filters.ids && filters.ids.length > 0) content = " <span style='color:red;'>已勾选的" + filters.ids.length + "个事项</span> ";
                let callback = () => {
                    this.loading = true;

                    filters.createdTimeStart = filters.submitTime?.[0];
                    filters.createdTimeEnd = filters.submitTime?.[1];
                    let createdTimeEnd = filters.submitTime?.[1]||null
                    if(createdTimeEnd){
                        if(typeof(createdTimeEnd) == 'string'){
                            createdTimeEnd = new Date(createdTimeEnd)
                        }
                        createdTimeEnd = new Date(createdTimeEnd.getTime()+24 * 60 * 60 * 1000).formatDate('yyyy-MM-dd')
                    }

                    filters.completeTimeStart = filters.overTime?.[0];
                    filters.completeTimeEnd = filters.overTime?.[1];
                    console.log('search',filters)
                    let completeTimeEnd = filters.overTime?.[1]||null
                    if(completeTimeEnd){
                        if(typeof(createdTimeEnd) == 'string'){
                            completeTimeEnd = new Date(completeTimeEnd)
                        }
                        completeTimeEnd = new Date(completeTimeEnd.getTime()+24 * 60 * 60 * 1000).formatDate('yyyy-MM-dd')
                    }

                    this.plugins.user.exportOrders({
                        ...filters,
                        createdTimeEnd,
                        completeTimeEnd,
                        jbdwId: (filters.jbdwId?filters.jbdwId:[]).concat(jbdwlistAll?.filter(x=>x.belongToId && filters.belongToId?.includes(x.belongToId)).map(x=>x.id))
                    }).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.alert("导出任务创建成功！", "任务执行需要花费一些时间，可稍后再点击右上角打开“系统任务”查看任务状态。", "success", ["查看任务状态", "稍后查看"]).then((ok) => ok && this.$router.push("/user/tasks"));
                        } else {
                            this.plugins.modal.alert("导出失败", res.code + "：" + res.msg, "error");
                        }
                    });
                };
                this.plugins.modal.alert("批量导出", "确定导出" + content + "吗？", "warning", ["确定导出", "再想想"]).then((ok) => ok && callback());
            },
            destroy() {
                if (this.loading) return;
                return true;
            },
            init() {
                this.zh = localStorage.getItem('zh')
                if (this.loading) return;
                this.loading = true;
                this.$root.$refs.navbar.init();
                this.plugins.user.call(async () => {
                    let res = await this.plugins.user.init();
                    if (res.code === 0) { }
                    return res;
                }, async () => {
                    if (this.access(this.$route.name)) return { code: 0 };
                    return this.env.xhrErrors.find((error) => error.code === 4);
                }).then((res) => {
                    this.loading = false;
                    this.$root.$refs.navbar.init();
                    if (res.code === 0) {
                        this.search();
                    } else if (res.code === 2) {
                        this.$root.$refs.navbar.login();
                    } else {
                        this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/home"));
                    }
                });
            },
        },
    };
</script>

<style lang="scss">
    .page-work-orders {
        overflow: hidden;
    }
</style>
